<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow">
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="设备编号">
                        <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                            v-model="dropDownData" />
                    </a-form-item>
                    <a-form-item label="设备名称">
                        <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                            v-model="dropDownData1" />
                    </a-form-item>
                    <a-form-item label="设备保养模板">
                        <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                            v-model="dropDownData2" />
                    </a-form-item>
                </a-form>
                <div>
                    <Toolbar :items="idTypes == 1 ? ['查询', '派工', '完成'] : idTypes == 2 ? ['查询'] : ['查询']"
                        @select="selectHandler" @dispatch="dispatchs" @complete="completes">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true" :default-active-key="1" @change="aTabsChanges">
                <a-tab-pane :key="1" title="未派工">
                    <a-spin :loading="pageLoading.value" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                            rowSelection="multiple" @grid-ready="gridReady3" style="height:calc(100% - 45px)"
                            :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="tableDataList3"
                            :columnDefs="tc" :localeText="localeText1" @columnResized="onColumnResized"
                            @columnMoved="onColumnMoved"></AgGridVuesCopys>
                        <paginationCopys :page-size-options="pagingList1" :total="fySelet.total" show-total show-jumper
                            show-page-size @change="PageSize" @page-size-change="change" style="justify-content: center"
                            :page-size="fySelet.size" :current="fySelet.page" />
                    </a-spin>
                </a-tab-pane>
                <a-tab-pane :key="2" title="待处理">
                    <a-spin :loading="pageLoading.value" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                            rowSelection="multiple" @grid-ready="gridReady" style="height:calc(100% - 45px)"
                            :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="tableDataList" :columnDefs="tc"
                            :localeText="localeText1" @columnResized="onColumnResized2" @columnMoved="onColumnMoved2">
                        </AgGridVuesCopys>
                        <paginationCopys :page-size-options="pagingList1" :total="fySelet.total" show-total show-jumper
                            show-page-size @change="PageSize" @page-size-change="change" style="justify-content: center"
                            :page-size="fySelet.size" :current="fySelet.page" />
                    </a-spin>
                </a-tab-pane>
                <a-tab-pane :key="3" title="已处理">
                    <a-spin :loading="pageLoading.value" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                            rowSelection="multiple" @grid-ready="gridReady2" style="height:calc(100% - 45px)"
                            :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="tableDataList2"
                            :columnDefs="tc" :localeText="localeText1" @columnResized="onColumnResized3"
                            @columnMoved="onColumnMoved3"></AgGridVuesCopys>
                        <paginationCopys :page-size-options="pagingList1" :total="fySelet.total" show-total show-jumper
                            show-page-size @change="PageSize" @page-size-change="change" style="justify-content: center"
                            :page-size="fySelet.size" :current="fySelet.page" />
                    </a-spin>
                </a-tab-pane>
            </a-tabs>

        </template>
        <a-modal :width="500" v-model:visible="visible" :on-before-ok="handleOk" @cancel="() => visible = false"
            :mask-closable="false">
            <template #title>
                派工
            </template>
            <a-form ref="formRef" :model="dataForm">
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item label="员工姓名" field="staff" label-col-flex="80px"
                            :rules="[{ required: true, message: '员工姓名必填' }]" :validate-trigger="['change', 'blur']">
                            <a-select popup-container="html" class="bacClass" :default-value="dataForm.staff"
                                :style="{ width: '250px' }" multiple v-model="dataForm.staff" allow-clear allow-search>
                                <a-option v-for="item in wxYgList" :value="item.name">{{
                                    item.name
                                }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="日期" field="startMaintainTime" label-col-flex="80px"
                            :rules="[{ required: true, message: '日期必填' }]" :validate-trigger="['change', 'blur']">
                            <a-date-picker popup-container="html" class="bacClass" v-model="dataForm.startMaintainTime"
                                style="width: 250px;" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </pageTabelLayout>
</template>
<script setup lang="ts">
import { post, get } from '@/api/http'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'

import { Message, Modal } from '@arco-design/web-vue'
import { pagingList } from "@/api/paging";
import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { saveOrUpdateGridState as saveOrUpdateGridState02 } from '@/hooks/useGridState'
import { saveOrUpdateGridState as saveOrUpdateGridState03 } from '@/hooks/useGridState'
const formRef = ref()

const headerShow = ref(true)

const pageData: any = reactive({
    dropDownData: '',
    dropDownData1: '',
    dropDownData2: '',
    showAdd: false,
    sideTitle: ''
})

const { dropDownData, dropDownData1, dropDownData2, showAdd, sideTitle } = toRefs(pageData)

const fySelet: any = reactive({
    total: 10,
    size: 10,
    page: 1
})

const idTypes = ref(1)
const pageLoading = ref(false)
const aTabsChanges = (e: any) => {
    idTypes.value = e
    fySelet.size = 10
    fySelet.page = 1
    fySelet.total = 0
    if (idTypes.value == 1) {
        selectList()
    } else if (idTypes.value == 2) {
        selectList1()
    } else if (idTypes.value == 3) {
        selectList2()
    }
}


const PageSize = (val: any) => {
    fySelet.page = val
    if (idTypes.value == 1) {
        selectList()
    } else if (idTypes.value == 2) {
        selectList1()
    } else if (idTypes.value == 3) {
        selectList2()
    }
}

const change = (val: any) => {
    fySelet.size = val
    if (idTypes.value == 1) {
        selectList()
    } else if (idTypes.value == 2) {
        selectList1()
    } else if (idTypes.value == 3) {
        selectList2()
    }
}

onMounted(() => {
    selectList()
})

const tableDataList: any = ref([])
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}

const tableDataList2: any = ref([])
const gridOption2 = ref()
const colState2 = ref()
const gridReady2 = (params: any) => {
    gridOption2.value = params.api
    colState2.value = params.columnApi
}

const tableDataList3: any = ref([])
const gridOption3 = ref()
const colState3 = ref()
const gridReady3 = (params: any) => {
    gridOption3.value = params.api
    colState3.value = params.columnApi
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1
}

const tc = [
    {
        showRowGroup: 'hide_def',
        "headerName": "",
        "checkboxSelection": true,
        "headerCheckboxSelection": true,
        "pinned": "left",
        "width": 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: "left",
    },
    {
        headerName: '序号',
        field: 'id',
        width: 150
    },
    {
        headerName: '保养模板',
        field: 'maintainName',
        width: 150
    },
    {
        headerName: '本次日期',
        field: 'timeType',
        width: 150
    },
    {
        headerName: '设备编号',
        field: 'machineCode',
        width: 150
    },
    {
        headerName: '设备类型',
        field: 'machineType',
        width: 150
    },
    {
        headerName: '设备名称',
        field: 'machine',
        width: 150
    },
    {
        headerName: '保养员工',
        field: 'staff',
        width: 150
    },
    // {
    //     headerName: '操作',
    //     field: 'slot',
    //     pinned: 'right',
    //     width: 120,
    //     cellRenderer: {
    //         template: `
    //       <a-space>
    //           <a-tag class="tagCss" @click="a">修 改</a-tag>
    //       </a-space>
    //       `,
    //         setup(props: any) {
    //             const a = () => {
    //                 updateList(props.params.data)// props.params.data
    //             }
    //             return {
    //                 a,
    //             }
    //         }
    //     }
    // },
]

const updateList = (e: any) => {
}

const selectHandler = () => {
    if (idTypes.value == 1) {
        selectList()
    } else if (idTypes.value == 2) {
        selectList1()
    } else if (idTypes.value == 3) {
        selectList2()
    }
}

function selectList() {
    pageLoading.value = true
    updateGridState01()
    post({
        url: 'temRepair/maintainDocument/findMaintainDocumentPage',
        data: {
            page: fySelet.page,
            limit: fySelet.size,
            "machine": pageData.dropDownData1,
            "machineCode": pageData.dropDownData,
            "maintainName": pageData.dropDownData2
        }
    }).then((res: any) => {
        gridOption3.value.setRowData(res.data.list)
        fySelet.total = res.data.total
    }).catch(console.log).finally(() => {
        pageLoading.value = false
    })
}

function selectList1() {
    pageLoading.value = true
    updateGridState02()
    post({
        url: 'temRepair/maintainDocument/findCompleteStatePage',
        data: {
            page: fySelet.page,
            limit: fySelet.size,
            completeState: 1,
            "machine": pageData.dropDownData1,
            "machineCode": pageData.dropDownData,
            "maintainName": pageData.dropDownData2
        }
    }).then((res: any) => {
        gridOption.value.setRowData(res.data.list)
        fySelet.total = res.data.total
    }).catch(console.log).finally(() => {
        pageLoading.value = false
    })
}

function selectList2() {
    updateGridState03()
    pageLoading.value = true
    post({
        url: 'temRepair/maintainDocument/findCompleteStatePage',
        data: {
            page: fySelet.page,
            limit: fySelet.size,
            completeState: 2,
            "machine": pageData.dropDownData1,
            "machineCode": pageData.dropDownData,
            "maintainName": pageData.dropDownData2
        }
    }).then((res: any) => {
        gridOption2.value.setRowData(res.data.list)
        fySelet.total = res.data.total
    }).catch(console.log).finally(() => {
        pageLoading.value = false
    })
}

const dataForm: any = reactive({
    "staff": "",
    "startMaintainTime": ""
})

const dispatchs = () => {
    if (gridOption3.value.getSelectedRows().length == 0 || gridOption3.value.getSelectedRows().length > 1) {
        return false
    }
    dataForm.staff = ''
    dataForm.startMaintainTime = ''
    post({
        url: 'admin/acl/user/findUserToken'
    }).then((res: any) => {
        if (res.code == 200) {
            if (res.data.data.departmentId == null || res.data.data.departmentId == 0) {
                Message.error('当前登陆账号无部门!')
                return
            }
            post({
                url: 'org/hrEmployee/getList',
                data: {
                    deleteState: 0,
                    obsoleteState: 0,
                    department_id: res.data.data.departmentId
                }
            }).then((resz: any) => {
                if (resz.code == 200) {
                    wxYgList.value = resz.data
                    dataForm.staff = gridOption3.value.getSelectedRows().map((res: any) => {
                        return res.staff
                    })
                    dataForm.startMaintainTime = gridOption3.value.getSelectedRows()[0].timeType
                    visible.value = true
                } else {
                    Message.error(resz.message)
                }
            })
        } else {
            Message.error(res.message)
        }
    })
}

const visible = ref(false)

const handleOk = async () => {
    const err = await formRef.value?.validate()
    if (!err) {
        let dataList = gridOption3.value.getSelectedRows().map((res: any) => {
            return {
                id: res.id,
                staff: dataForm.staff.toString(),
                startMaintainTime: dataForm.startMaintainTime
            }
        })
        const res = await post({
            url: 'temRepair/maintainDocument/DispatchingMaintainDocument',
            data: dataList
        })
        if (res.code == 200) {
            Message.success(res.message)
            selectList()
            selectList1()
            return true
        } else {
            Message.error(res.message)
            return false
        }
    } else {
        return false
    }
}

const wxYgList: any = ref([])

const completes = () => {
    if (gridOption3.value.getSelectedRows().length === 0) {
        return false
    }
    Modal.confirm({
        title: '系统提示',
        content: '确认完成选中的数据?',
        onOk() {
            post({
                url: 'temRepair/maintainDocument/updateCompleteState',
                data: gridOption3.value.getSelectedRows().map((o: any) => {
                    return o.id
                })
            }).then(({ code, data }: any) => {
                if (code === 200) {
                    Message.success({
                        content: '成功',
                        duration: 5000
                    })
                    fySelet.page = 1
                    selectList()
                    selectList1()
                    selectList2()

                } else {
                    Message.error({
                        content: '完成失败',
                        duration: 5000
                    })
                }

            })
        }
    })
}

const localeText1: any = ref(localeText)
const pagingList1: any = ref(pagingList)
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('MaintenanceVue01', gridOption, colState, tc)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
const { saveGridState: saveGridState02, updateGridState: updateGridState02 } = saveOrUpdateGridState02('MaintenanceVue02', gridOption2, colState2, tc)
const onColumnMoved2 = () => {
    saveGridState02()
}
const onColumnResized2 = () => {
    saveGridState02()
}
const { saveGridState: saveGridState03, updateGridState: updateGridState03 } = saveOrUpdateGridState03('MaintenanceVue03', gridOption3, colState3, tc)
const onColumnMoved3 = () => {
    saveGridState03()
}
const onColumnResized3 = () => {
    saveGridState03()
}
</script>
<style lang="less" scoped>
:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}
</style>